import java.util.Arrays;
import java.util.DoubleSummaryStatistics;

/**
 * Created with IntelliJ IDEA.
 * User: 12629
 * Date: 2021/11/9
 * Time: 10:11
 * Description:
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }


    public void shiftDown(int parent,int len) {
        int child = (2*parent)+1;
        //这棵树没有调整完，最起码 有左树
        while (child < len) {
            if(child+1 < len && this.elem[child] < this.elem[child+1]) {
                child++;
            }
            //child下标一定是左右孩子的最大值
            if(this.elem[child] > this.elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = 2*parent+1;
            }else {
                break;
            }
        }
    }

    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            this.elem[i] = array[i];
            this.usedSize++;
        }

        for (int parent =  (this.usedSize-1-1)/2; parent >= 0 ; parent--) {
            shiftDown(parent,this.usedSize);//10
        }
    }

    public void shiftUp(int child) {
        int parent = (child-1)/2;
        while (child > 0) {
            if(this.elem[child] > this.elem[parent]) {
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }


    public void push(int val) {
        if(isFull()) {
            this.elem = Arrays.copyOf(this.elem,2*this.elem.length);
        }
        this.elem[this.usedSize] = val;
        this.usedSize++;
        shiftUp(this.usedSize-1);
    }

    public boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    public boolean isEmpty() {
        return this.usedSize == 0;
    }

    public int pop() {
        if(isEmpty()) {
            return -1;
        }
        int tmp = elem[0];
        elem[0] = elem[this.usedSize-1];
        elem[this.usedSize-1] = tmp;
        this.usedSize--;
        shiftDown(0,this.usedSize);
        return tmp;
    }

    public int peek() {
        if(isEmpty()) {
            return -1;
        }
        return this.elem[0];
    }
}
